//
// Created by mio on 25-5-20.
//

#include "RemoteManager.h"

RemoteManager::RemoteManager() : pullerWgt_(nullptr), event_loop_(nullptr), sig_conn_(nullptr)
{
    event_loop_.reset(new EventLoop(2));
}

RemoteManager::~RemoteManager()
{
    Close();
}

void RemoteManager::Init(const QString &sigIp, uint16_t port, const QString &code)
{
    TcpSocket socket;
    socket.Create();
    if (!socket.Connect(sigIp.toStdString(), port)) {
        qDebug() << "Failed to connect to SigServer" << sigIp << ":" << port;
        return;
    }
    qDebug() << "连接信令服务器成功";
    //生成一个信令连接器
    sig_conn_.reset(new SigConnection(event_loop_->GetTaskScheduler().get(), socket.GetSocket(), code));
    sig_conn_->SetStopStreamCallBack([this]() {
        this->HandleStopStream();
    });
    sig_conn_->SetStartStreamCallBack([this](const QString& streamAddr) {
        return this->HandleStartStream(streamAddr);
    });
}

void RemoteManager::StartRemote(const QString &sigIp, uint16_t port, const QString &code)
{
    pullerWgt_.reset(new PullerWgt(event_loop_.get(), nullptr));
    pullerWgt_->show();
    if (!pullerWgt_->Connect(sigIp, port, code))
    {
        qDebug() << "远程连接失败";
        return;
    }
    qDebug() << "远程连接成功";
    pullerWgt_->StartPull();
}

void RemoteManager::HandleStopStream()
{
    RtmpPushManager::Close();
}

bool RemoteManager::HandleStartStream(const QString &streamAddr)
{
    //开始推流
    qDebug() << "Start push: " << streamAddr;
    return this->Open(streamAddr); // RtmpPushManager::Open
}

void RemoteManager::Close()
{
    if(sig_conn_->isPusher())
    {
        //停止推流
        RtmpPushManager::Close();
    }
}
